import type { ILessonResult } from "@/pages/lowPricedCourse/trialCourseHome/courseList/index.vue";
import type { IResult, IRolePlayResult } from "./index.vue";
import API from "@/api";

export const requestNecessaryData = (sectionId: number): Promise<IRolePlayResult> => {
  return new Promise((resolve, reject) => {
    API.rolePlayData({ section_id: sectionId })
      .then((res) => {
        let pageData = res as IResult;

        let isRelearn = pageData.rolePlay.every((message) => {
          if (message.role === 1) {
            return true;
          }
          if (message.user_voice && message.user_voice.length > 0) {
            return true;
          }
          return false;
        });

        if (isRelearn) {
          pageData.rolePlay.forEach((message, index) => {
            if (message.role === 0) {
              message.user_voice = undefined;
              message.analysis = undefined;
            }
          });
        }
        var currentMessageIndex = -1;
        var lastUserMessageIndex = -1;
        for (var i = 0; i < pageData.rolePlay.length; i++) {
          let message = pageData.rolePlay[i];
          if (message.role === 0) {
            if (!message.user_voice || message.user_voice.length == 0) {
              currentMessageIndex = lastUserMessageIndex + 1;
              break;
            }
          }
        }

        for (var i = pageData.rolePlay.length - 1; i >= 0; i--) {
          let message = pageData.rolePlay[i];
          if (message.role === 0) {
            lastUserMessageIndex = i;
            break
          }
        }


        let data: IRolePlayResult = {
          isRelearn: isRelearn,
          isNeedLaunchPage: isRelearn || currentMessageIndex === 0,
          data: { userImg: pageData.userImg, systemImg: pageData.systemImg, toCompPage: pageData.toCompPage, rolePlay: pageData.rolePlay, currentMessageIndex: currentMessageIndex, lastUserMessageIndex: lastUserMessageIndex },
        };
        resolve(data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
